package com.cwj.film.AOP;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cwj.common.Beans.film.requestBeans;
import com.cwj.common.domain.upFilm;
import com.cwj.common.domain.user;
import com.cwj.common.utils.utils;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Closeable;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Aspect
@Component
@Order(0)
public class upFilmAop {
    @Resource
    HttpServletRequest request;

    @Resource
    private com.cwj.film.dao.upFilmDao upFilmDao;
    @Resource
    private com.cwj.film.dao.userDao userDao;
    @Pointcut("execution(* com.cwj.film.service.inter.upFilm.upFilm(..))")
    private void upFilmPointcut(){}
    @Before("upFilmPointcut()")
    public void createRequestBeans(){
        requestBeans requestBeans=new requestBeans();
        requestBeans.setCloseableList(new ArrayList<>());
        requestBeans.setFileList(new ArrayList<>());
        request.setAttribute("requestBeans",requestBeans);
    }
    @AfterReturning("upFilmPointcut()")
    public Boolean close() throws Exception {
        List<Closeable>  closeableList = ((requestBeans)request.getAttribute("requestBeans")).getCloseableList();

        if(closeableList==null||closeableList.size()==0){
            return false;
        }
        for (Closeable closeable : closeableList) { closeable.close(); }
         request.setAttribute("status","yes");

        return true;
    }
    @AfterThrowing("upFilmPointcut()")
    public Boolean deleteFile() throws Exception {
        request.setAttribute("status","no");
        close();
        List<File> fileList = ((requestBeans) request.getAttribute("requestBeans")).getFileList();

        fileList.stream().filter(File::isFile).forEach(File::delete);
        fileList.stream().filter(File::isDirectory).forEach(file -> {
            File[] files = file.listFiles();
            if(files!=null) {
                Arrays.stream(files).forEach(File::delete);
                file.delete();
            }
        });
        return false;
    }
    @After("upFilmPointcut()")
    public void logUpFilm(){
        upFilm upfilm = new upFilm();
        Object film = request.getAttribute("film");
        BeanUtils.copyProperties(film,upfilm);
        upfilm.setStatus( request.getAttribute("status").toString());

        Map<String, String> userByCookie = utils.GetUserByCookie(request.getCookies());
        List<Object> uidList = userDao.selectObjs(new QueryWrapper<user>().allEq(userByCookie).select("uid"));
        upfilm.setUid(uidList.size()>0 ? (Integer) uidList.get(0) : 0);
        upFilmDao.insert(upfilm);
    }
    }

